/**
 * 
 */
package nio3A2B;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * @author wudan_js
 *
 */
public class NioServer {
	private static Set<SocketChannel> clients=new HashSet<SocketChannel>();
	
	public static void main(String[] args) {
		ServerSocketChannel serverChannel;
		Selector selector;
		
		try{
			//服务端的准备
			serverChannel= ServerSocketChannel.open();
			ServerSocket serverSocket=serverChannel.socket();
			serverSocket.bind(new InetSocketAddress(12345));
			serverChannel.configureBlocking(false);
			selector=Selector.open();
			serverChannel.register(selector, SelectionKey.OP_ACCEPT);
		} catch (IOException e){
			e.printStackTrace();
			return;
		}
		
		while(true){
			try {
				selector.select();
				System.out.println("======select========");
			} catch (IOException e) {
				e.printStackTrace();
				break;
			}
			Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
			
			while(iterator.hasNext()){
				SelectionKey key=iterator.next();
				iterator.remove();
				
				try {
					if(key.isAcceptable()){
						System.out.println("=============accept============");
						ServerSocketChannel server = (ServerSocketChannel) key.channel();
						SocketChannel client=server.accept();//接受客户端的请求
						client.configureBlocking(false);//客户端 服务端 全都设置为 非阻塞
						
						clients.add(client);
						client.register(key.selector(), SelectionKey.OP_READ);
					}
					if(key.isReadable()){
						System.out.println("=============read==============="+clients);
						SocketChannel client=(SocketChannel) key.channel();
						ByteBuffer buffer=ByteBuffer.allocate(1024);
						if(client.read(buffer)>0){
							Iterator<SocketChannel> it=clients.iterator();
							while(it.hasNext()){
								SocketChannel other=it.next();
								if(other != client){
									buffer.flip();
									other.write(buffer);
								}
							}
						}
						
						key.interestOps(SelectionKey.OP_READ);
					}
				} catch (IOException e) {
					e.printStackTrace();
					
				}
			}
		}
	}
}
